const response = require('./response')
const jwt = require("jsonwebtoken");
const secret = 'tuisa';
const refreshSecret = 'refreshTuisa'; // 用于 refreshToken 的密钥
const { noTokenPath } = require("./constData")

const sign = (data, usefulTime = '24h') => {
    return jwt.sign(data, secret, { expiresIn: usefulTime });
};

// 生成 refreshToken 的函数
const signRefreshToken = (data, usefulTime = '7d') => {
    return  jwt.sign(data, refreshSecret, { expiresIn: usefulTime });
};

// 验证 refreshToken 的函数
const verifyRefreshToken = (ctx,refreshToken) => {
    if (!refreshToken) {
        return response.error(ctx, { message: '无刷新凭证，请重新登录', status: 401 });
    }
    try {
        const decoded = jwt.verify(refreshToken, refreshSecret);
        return decoded;
    } catch (error) {
        return response.error(ctx, { message: '刷新凭证过期，请重新登录', status: 401 });
    }
};

const verify = async (ctx, next) => {
    if (noTokenPath.includes(ctx.path)) {
        return await next();
    }
    let authHeader = ctx.request.header.authorization || ctx.headers.authorization
    if (!authHeader) {
        delete ctx.userId
        return response.error(ctx, { message: '无登陆凭证', status: 401 })
    }
    try {
        let res = jwt.verify(authHeader.split(' ')[1], secret);
        if (res) {
            ctx.userId = res.id; // 假设JWT载荷中有一个'id'字段
            await next()
        } else {
            delete ctx.userId
            return response.error(ctx, { message: '登陆凭证过期', status: 403 })
        }
    } catch (error) {
        if(error){
            response.error(ctx, { message: '登陆凭证验证失败', status: 401 })
        }
    }
};

module.exports = {
    sign,
    signRefreshToken,
    verifyRefreshToken,
    verify,
};
